package org.hry.socket.bio.shortlink;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

/**
 * @Desc
 * @Author houry
 * @Date 2021/2/23 16:54
 **/
public class SocketServer {
    public static void main(String[] args) throws IOException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                20,
                20,
                5L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                new SocketThreadFactory("自定义socket线程池"),
                new ThreadPoolExecutor.DiscardPolicy());
        ServerSocket server = new ServerSocket(8888);
        while(true) {
            Socket socket = server.accept();
            executor.execute(() ->{
                try(InputStream in = socket.getInputStream();OutputStream out = socket.getOutputStream();){
                    byte[] bytes = new byte[1024];
                    out.write("这里是服务端发送的数据".getBytes(StandardCharsets.UTF_8));
                    // 告诉客户端，我已经发送完一部分数据了。如果不调用的话，客户端是接受不到结束信号的
                    socket.shutdownOutput();
                    StringBuffer sb = new StringBuffer();
                    int len;
                    while ((len = in.read(bytes)) != -1) {
                        sb.append(new String(bytes, 0, len));
                    }
                    // 接收到信息，拿到接收的信息之后就可以处理了。
                    System.out.println("接收到消息：" + sb.toString());
                    socket.shutdownInput();
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
